import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";

// 定义RequestInit接口以解决类型错误
interface RequestInit {
  method?: string;
  headers?: Record<string, string>;
  body?: string;
  mode?: string;
  credentials?: string;
  cache?: string;
  redirect?: string;
  referrerPolicy?: string;
}

// API基础URL
const API_BASE_URL = "/api";
// 请求头配置
const getHeaders = () => {
  const headers = new Headers();
  headers.append("Content-Type", "application/json");
  
  // 如果有认证token，添加到请求头
  const token = localStorage.getItem("token");
  if (token) {
    headers.append("Authorization", `Bearer ${token}`);
  }
  
  return headers;
};

// API请求工具函数
export async function apiRequest<T>(
  endpoint: string, 
  options: RequestInit = {}
): Promise<T> {
  const url = `${API_BASE_URL}${endpoint}`;
  
  const config: RequestInit = {
    ...options,
    headers: getHeaders(),
  };
  
  try {
    const response = await fetch(url, config);
    
    // 处理非2xx状态码
    if (!response.ok) {
      const errorData = await response.json().catch(() => null);
      throw new Error(errorData?.message || `请求失败: ${response.status}`);
    }
    
    // 处理空响应
    if (response.status === 204) {
      return {} as T;
    }
    
    return await response.json();
  } catch (error) {
    console.error("API请求错误:", error);
    throw error;
  }
}

// 登录API
export async function loginUser(credentials: { username: string; password: string }) {
  return apiRequest<{ token: string; user: any }>("/ai-role-play/auth/login", {
    method: "POST",
    body: JSON.stringify(credentials),
  });
}

// 注册API
export async function registerUser(userData: { username: string; password: string; email: string }) {
  return apiRequest<{ token: string; user: any }>("/ai-role-play/auth/register", {
    method: "POST",
    body: JSON.stringify(userData),
  });
}

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}